'''
@author niann
url:https://www.gequbao.com/
'''
import json
from random import random

import requests as req
import re
from bs4 import BeautifulSoup

# 输入搜索关键字,自动下载
search_text = "周杰伦"
req_info = req.get("https://www.gequbao.com/s/{}".format(search_text))

satrt_index = req_info.text.find('''<div class="row mb-3">
                    <div class="col-5"><i class="fa fa-music"></i> 歌名</div>
                    <div class="col-4"><i class="fa fa-user-circle"></i> 歌手</div>
                    <div class="col-3 text-right">操作</div>
                </div>''')
end_index = req_info.text.find('''<div class="alert alert-warning" role="alert">
                        <a class="font-weight-bold text-secondary" data-toggle="collapse" href="#collapseNotice" aria-expanded="false" aria-controls="collapseExample" style="text-decoration:underline">
                            搜索结果不是你想要的？
                        </a>
                    </div>''')
html = req_info.text[4964:63938]
soup = BeautifulSoup(html, 'html.parser')
row_list = soup.find_all('div', class_='col-5 col-content')
music_list = dict()
if row_list is not None:
    for row in row_list:
        if row is not None:
            music_name = row.text
            music_info = row.find_all_next("a")
            music_url = BeautifulSoup(music_info.__str__(), 'html.parser').find('a').get("href").split("/")[-1]
            music_list.update({music_name: music_url})
i = 0
import time
import random

for music in music_list:
    try:
        file_url = "https://www.gequbao.com/api/play_url?id={}&json=1".format(music_list[music])
        json_str = json.loads(req.get(file_url).text)
        download_url = json_str['data']['url']
    except:
        raise ValueError("请求太频繁")  # 报这个错就将58行i == 5 设置低一点
    # 下载文件
    file_resp = req.get(download_url)
    if file_resp.status_code == 200:
        music = music.strip()
        # 下载路径
        path = "C:\\Users\\Administrator\\Music\\"
        music = music.strip(".")
        with open("{}.mp3".format(path, music), 'wb') as f:
            f.write(file_resp.content)
            print("{} downloaded success".format(music))
    else:
        print("网络异常")
    i += 1
    if i == 5:
        print('暂停')
        time.sleep(random.randint(20, 30))
        i = 0
